package com.jeeplus.test.jlnu.archivalInfo.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.jeeplus.test.jlnu.archivalInfo.domain.vo.ArchivalInfoExcelVO;
import com.jeeplus.test.jlnu.archivalInfo.service.ExcelArcService;

import java.util.ArrayList;
import java.util.List;

public class ArchivalInfoDataListener extends AnalysisEventListener<ArchivalInfoExcelVO> {



    private final ExcelArcService excelArcService;
    private final ArchivalInfoDataListener.ProgressCallback progressCallback;
    private static final int BATCH_COUNT = 500;
    private final String officeId;
    private List<ArchivalInfoExcelVO> dataList = new ArrayList<>();
    private int totalRecords;
    private int currentRecords;



    public ArchivalInfoDataListener(ExcelArcService excelArcService, ArchivalInfoDataListener.ProgressCallback progressCallback, int totalRecords, String officeId) {
        this.excelArcService = excelArcService;
        this.progressCallback = progressCallback;
        this.totalRecords = totalRecords;
        this.officeId = officeId;
    }







    @Override
    public void invoke(ArchivalInfoExcelVO data, AnalysisContext context) {

        data.setOfficeId(officeId);
        dataList.add(data);
        currentRecords++;

        if (dataList.size() >= BATCH_COUNT) {
            saveDataToDatabase();
            dataList.clear();
        }

        updateProgress();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (!dataList.isEmpty()) {
            saveDataToDatabase();
            dataList.clear();
        }
        updateProgress();
    }

    private void saveDataToDatabase() {
        if (!dataList.isEmpty()) {
            excelArcService.insertDataArch(dataList);
        }
    }

    private void updateProgress() {
        int progress = (int) (((double) currentRecords / totalRecords) * 100);
        progressCallback.onProgress(progress);
    }

    public interface ProgressCallback {
        void onProgress(int progress);
    }
}
